package org.changchen.fgt.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.io.file.FileReader;

public class NovelUtil {
	
	
	private static final String REGEX = "(^\\s*第)([零一二三四五六七八九十百千万]{1,9})([章节卷集部篇回])(\\s+)(.*)";

	
	public static void main(String[] args) {
		
		Map<Integer,Map<String,Object>> chapterMap = new HashMap<>();
		
		FileReader reader = new FileReader("D:/media/大奉打更人.txt");
		
		List<String> lines = reader.readLines();
		
		Integer chapterIdx = 0;
		Integer begin = 0;
		Integer end = 0;
		String chapterName = null;
		
		for(int i=0;i<lines.size();i++) {
			String line = lines.get(i);
			String title = discernChapter(line);
			if(title != null) {
				if(begin > 0) {
					end = i;
					Map<String,Object> contentMap = new HashMap<>();
					contentMap.put("title", chapterName);
					contentMap.put("begin", begin);
					contentMap.put("end", end);
					chapterMap.put(chapterIdx, contentMap);
				}
				begin = i;
				chapterName = title;				
				chapterIdx++;
			}
		}
		
		StringBuilder chapterLabel = new StringBuilder();
		int i = 1;
		for(Integer key : chapterMap.keySet()) {
			Map<String,Object> contentMap = chapterMap.get(key);
			String titleLabel = (String) contentMap.get("title");
//			Integer beginLabel = (Integer) contentMap.get("begin");
//			Integer endLabel = (Integer) contentMap.get("end");
			chapterLabel.append(key + "-" + titleLabel + "\t");
			if(i%3 == 0) {
				chapterLabel.append("\r\n");
			}			
			i++;
		}
		System.out.println(chapterLabel.toString());
		
		Scanner scanner = new Scanner(System.in);
		while(true) {
			System.out.println("请选择章节序号（输入-1退出）:");			
			Integer chooseChapter = scanner.nextInt();
			if(chooseChapter < 0) {
				System.out.println("欢迎使用！");				
				break;
			}
			
			Map<String,Object> contentMap = chapterMap.get(chooseChapter);
			chapterName = (String) contentMap.get("title");
			begin = (Integer) contentMap.get("begin");
			end = (Integer) contentMap.get("end");
			
			
			List<String> subList = lines.subList(begin, end);
			subList.forEach(line -> {
				System.out.println(line);
			});
			
			System.out.println(chooseChapter + "-" +chapterName + " 已阅读结束！");
		}	
		scanner.close();
	}
	
	
	
	/**   
	 * @Title:      discernChapter   
	 * @Description:正则表达式匹配章节标题   
	 * @param:      @param line
	 * @param:      @return      
	 * @return:     String      
	 * @throws   
	 */
	public static String discernChapter(String line) {
		
		if(line == null || line.length() == 0) {
			return null;
		}
		
		Pattern pattern = Pattern.compile(REGEX);
		
		Matcher matcher = pattern.matcher(line);
		if(matcher.find()) {
			return matcher.group();
		}

		return null;
	}
	
	
}